import java.util.Arrays;


public class Node {
	Node[] _child;
	Board _board;
	byte[] _moves;
	
	Player alternatePlayer(Player player) {
		if (player == Player.ONE) {
			return Player.TWO;
		} else {
			return Player.ONE;
		}
	}
	
	int getValue(Player player) {
		int removePieces = 0;
		int[] removeMoves = new int[_moves.length];
		Error error = Error.SUCCESS;;
		GameStateEnum _gameStateEnum = _board.getGameState();
		
		int value = 0;
		Player tempPlayer = Player.TWO;
		for (int i=0; i<_moves.length; ++i) {
			error = _board._columns[_moves[i]].addPiece(tempPlayer);
			if (error == Error.COLUMN_NOT_ENOUGH_SPACE) {
				if (tempPlayer != Player.TWO)
					value += 100000;
				else
					value += -100000;
				break;
			} else {
				removeMoves[removePieces++] = _moves[i];
				if (_board._GameState.isWinningState(_board._GameState.evaluateBoardPlacedPieceWin(_board._lastTile))) {
					if (tempPlayer == Player.TWO)
						value += 100000;
					else
						value += -100000;
					break;
				}
				tempPlayer = alternatePlayer(tempPlayer);
				
			}
		}
		
		if (error == Error.COLUMN_NOT_ENOUGH_SPACE) {
			//_value = 0;
		} else {
			_board._GameState.generateCounts(player);
			if (player == Player.TWO)
				value += 320*_board._GameState._3Count + 40*_board._GameState._2Count + 10*_board._GameState._1Count;
			else {
				value -= 320*_board._GameState._3Count + 40*_board._GameState._2Count +10* _board._GameState._1Count;
			}
		}
		
		
		for (int i=removePieces-1; i>=0; --i) {
			//--_board._numPieces;
			_board._columns[removeMoves[i]].removeTopPiece();
		}
		_board._GameState._GameStateEnum = _gameStateEnum;
		return value;
	}
	
	void generateChildren(int depth) {
		if (depth > 0) {
			_child = new Node[_board._numColumns];
			for (int i = 0; i < _board._numColumns; ++i) {
				_child[i] = new Node();
				_child[i]._board = _board;
				_child[i]._moves = new byte[_moves.length+1];
				_child[i]._moves = Arrays.copyOf(_moves, _moves.length+1);
				_child[i]._moves[_moves.length] = (byte)i;
				_child[i].generateChildren(depth-1);
			}
			_moves = null;
		}
	}
}
